var attendanceType;
var id;
var groupid;
var iconid;
var subid;
var menuid;
var businessId;
var MapType =1;
var equipmentTypesss;

$(function(){
	groupid = ly.getUrlParam("groupid");
	iconid = ly.getUrlParam("iconid");
	subid = ly.getUrlParam("subid");
	menuid = ly.getUrlParam("menuid");	

	attendanceType = ly.getUrlParam("attendanceType");
	id = ly.getUrlParam("id");
	if(attendanceType == 2){
		$(".body_title").html("编辑");
		  $(".form").getForm({
	        id: id,
	        ajaxform:true
	   },function (data) {


			$("#isUsing").getSelect({
				type:"radio",
				asName:"isUsing",
				list:[
					{value:"1",display:"是"},
					{value:"0",display:"否"}
				],
				default:data.isUsing			
			});
			// $("#equipmentType").getSelect({
			// 	type:"radio",
			// 	asName:"equipmentType",
			// 	code:"equipmentType",
			// 	default:data.equipmentType		
			// });

			request({
				url: site.gateUrl + '/dictBasic/selectDictBasicList',
					data:{size:1000,num:1,code:'equipmentType'},
				ajaxform:true,
				type: 'get',
				callback: function(r) {
					//var equipmentTypeId = data.equipmentType == rs[i].value ?  :
					  var rs =  r.result.list
					  var htmls = '';
					  var htmls2='';
					  var sum = [];
				
					  var parentids	;
		
					//  var parentids	= removeRepeatStr(rs[data.equipmentType].id)
						for (let i = 0; i <rs.length; i++) {

								if( rs[i].value == data.equipmentType ){
									parentids = rs[i].id
									console.log(rs[i].id)
									  if(rs[i].parentId==null || rs[i].parentId=='' ||rs[i].parentId=='null'){
										$('#equipmentTypeHide').addClass('hide')
									
									  }else{
										$('#equipmentTypeHide').removeClass('hide')
									  }
								}
							   if(rs[i].parentId==null || rs[i].parentId=='' ||rs[i].parentId=='null'){
						
							
								htmls+='<label class="rad"><input type="radio"value="'+rs[i].value+'" data-id='+rs[i].id+' data-parentId='+rs[i].parentId+' name="equipmentType" ><b></b>'+rs[i].display+'</label>';						
							   }else{
									
								
								//$('#equipmentTypeHide').removeClass('hide')
								htmls2+='<label class="rad"><input type="radio"value="'+rs[i].value+'" data-id='+rs[i].id+' data-parentId='+rs[i].parentId+' name="equipmentType2s" ><b></b>'+rs[i].display+'</label>';						
							   }
						//	   console.log(parentids+'++++++++++++++')   //b26879696b8f47cbb370ddf3e46ec3b0
							//    console.log(rs[i].parentId)   //849e6bbdb8d04cfc8b52ae2fc631fc5d

							//    if(rs[i].parentId!=null  &&  rs[i].parentId  == parentids){

							// 	sum.push(rs[i])
							
							// 	 } 
						
								//  if( $("input[name='equipmentType']").val() == data.equipmentType ){
								// 	$("input[name='equipmentType']").attr('checked','true')
								//  }else if($("input[name='equipmentType2']").val() == data.equipmentType){
								// 	$("input[name='equipmentType2']").attr('checked','true')
								//  }
						
						}
						
						$('#equipmentType2s').html(htmls2)
						$('#equipmentType').html(htmls)
						for (let i = 0; i<rs.length;i++){
							if(data.equipmentType == rs[i].value){
								var tmp = rs[i].parentId;
								console.log(tmp);
								for (let j=0 ; j<rs.length;j++){
									if(rs[j].id == tmp){
										console.log(rs[j].value)
										 $("#equipmentType input[value="+rs[j].value+"]").attr("checked",true)
										
									}else{
										$("#equipmentType input[value="+data.equipmentType+"]").attr("checked",'checked')
									}
								}
							}
						}
						/* $("#equipmentType").getSelect({
							type: "radio",
							asName: "equipmentType",
							code: "equipmentType",
							default: 3,
							list:rs
						}); */
						$("#equipmentType2s input[value="+data.equipmentType+"]").attr("checked",'checked')
					


					function removeRepeatStr(str){
						var newStr = '';
						var len = str.length;
						for(var i=0; i<len; i++){
							if(newStr.indexOf(str[i])==-1){
								newStr = newStr + str[i];
							}
						}
						return newStr;
					}
				
				}
			});


               $("#log").val(data.log);
               $("#lat").val(data.lat);
               $("#equipmentAddress").val(data.equipmentAddress);
			   $("#writeAddress").removeClass("hide");
			   
			   $("#setMap").addClass("hide");
			
			   
	    });
	    $('#addr').singleMapSelector({
            address: '',
            lng: '',
            lat: ''
        },function(d){
            orgAdd = d.address;
            latitude = d.lat;
            longitude = d.lng;
            $("#log").val(longitude);
           	$("#lat").val(latitude);
           	console.log('orgAdd',orgAdd)
           	$("#equipmentAddress").val(orgAdd);
		});
		
	}else{
		$("#isUsing").getSelect({
			type:"radio",
			asName:"isUsing",
			list:[
				{value:"1",display:"启用"},
				{value:"0",display:"禁用"}
			],
			default:'1'			
		});
		// $("#equipmentType").getSelect({
		// 	type:"radio",
		// 	asName:"equipmentType",
		// 	code:"equipmentType",
		// 	default:1		
		// });
			
		request({
			url: site.gateUrl + '/dictBasic/selectDictBasicList',
				data:{size:1000,num:1,code:'equipmentType'},
			ajaxform:true,
			type: 'get',
			callback: function(r) {
				
				  var rs =  r.result.list
				  var htmls = '';
					for (let i = 0; i <rs.length; i++) {
					
						   if(rs[i].parentId==null || rs[i].parentId=='' ||rs[i].parentId=='null'){
						
							htmls+='<label class="rad"><input type="radio"value="'+rs[i].value+'" data-id='+rs[i].id+' data-parentId='+rs[i].parentId+' name="equipmentType" ><b></b>'+rs[i].display+'</label>';						
						
						}
					}

				$('#equipmentType').html(htmls)
			}
		});


		/**
		 * 通过“请选择地址设置的经纬度”
		 */
		$('#addr').singleMapSelector({
            address: '',
            lng: '',
            lat: ''
        },function(d){
            orgAdd = d.address;
            latitude = d.lat;
            longitude = d.lng;
           // $(".add").html("<i class='iconfont icon-shanchu shanchu'></i>&nbsp;&nbsp;&nbsp;<span>"+d.address+"("+longitude+","+latitude+")</span>");
           $("#log").val(longitude);
           $("#lat").val(latitude);
           console.log('orgAdd:',orgAdd);
           $("#equipmentAddress").val(orgAdd);
           $("#writeAddress").removeClass("hide");
        });
		
	}
	$("#equipmentType").on("click","input[name='equipmentType']",function(){
		
		
		var thatId = $(this).attr('data-id');
		console.log(thatId)
		equipmentTypesss = $(this).val()
		request({
			    url: site.gateUrl + '/dictBasic/selectDictBasicList',
				data:{size:1000,num:1,code:'equipmentType'},
		     	ajaxform:true,
			    type: 'get',
		 	callback: function(r) {
				
				  var thisId ;
				  var IdArr=[];
				  var rs =  r.result.list
				  var htmls = '';
			
					for (let i = 0; i <rs.length; i++) {
						   if(rs[i].id == thatId){
							  thisId = rs[i].id
						   }
					}
					for (let i = 0; i <rs.length; i++) {
						console.log(thisId);
					   if(rs[i].parentId!=null && thisId == rs[i].parentId ){
							 IdArr.push(rs[i])
					   }
		 	        }
			   
					    console.log(IdArr);
					for (let i = 0; i < IdArr.length; i++) {
				    	  //console.log(IdArr[i]);
						  htmls+='<label class="rad"><input type="radio"value="'+IdArr[i].value+'" name="equipmentType2s" ><b></b>'+IdArr[i].display+'</label>'
					}
					
					if(IdArr.length == 0){
						$('#equipmentTypeHide').addClass('hide')
					}else{
						$('#equipmentTypeHide').removeClass('hide')
					}
				$('#equipmentType2s').html(htmls)
			}
		});
		// if(that == 3){
		// 	$('#equipmentTypeHide').removeClass('hide')
		// }else{
		// 	$('#equipmentTypeHide').addClass('hide')
		// }
	});

	$("#equipmentType2s").on("click","input[name='equipmentType2s']",function(){
		    
			equipmentTypesss = $(this).val()
			console.log(equipmentTypesss)

	});



	$("body").on("click","input[name='map']",function(){
		MapType = this.value;
		console.log(MapType)
		if(MapType == '2'){
			$("#Map2").removeClass("hide");
			$("#Map1").addClass("hide");
			$("#writeAddress").addClass("hide");
			//selectbusinessList(businessId);
		}else{
			$("#Map2").addClass("hide");
			$("#Map1").removeClass("hide");
		}

	});
	//获取到选择的值
	$("body").on("click","input[name='userType']",function(){
		var userType = this.value;
		if(userType == '2'){
			$("#changeBusinessId").removeClass("hide");
			selectbusinessList(businessId);
		}else{
			$("#changeBusinessId").addClass("hide");
		}
	});

	//提交
    $("body").on("click","#save-btn-commodityClassification",function(event){
        event.preventDefault();
	
		// if(equipmentTypesss == '' || equipmentTypesss == null|| equipmentTypesss == undefined){
		// 	ly.toast("请输入完整信息");
		// 	return false;
		//  }
		console.log('$("#log2").val()=',$("#log2").val());
		console.log('$("#lat2").val()=',$("#lat2").val());
		console.log('$("#lat").val()=',$("#lat").val());
		console.log('$("#lat").val()=',$("#lat").val());
		if(attendanceType ==1){
			if(MapType == 1){

				if($("#log").val()=="" || $("#lat").val()=="" || $("#equipmentAddress").val()=="" || $("#equipmentName").val()==""){
					ly.toast("请输入完整信息");
					return false;
				}

			}else if(MapType == 2){

				if($("#log2").val()=="" || $("#lat2").val()==""|| $("#equipmentName").val()=="" ){
					ly.toast("请输入完整信息");
					return false;
				}else{
					//验证经纬度的范围取值 和数字格式正确

					if(logIsNotNumber($("#log2").val())){
						ly.toast("经度必须为数字");
						return false;
					}

					if(validateLogISError($("#log2").val())){
						ly.toast("请输入正确的经度");
						return false;
					}

					if(latIsNotNumber($("#log2").val())){
						ly.toast("纬度必须为数字");
						return false;
					}

					if(validateLatISError($("#lat2").val())){
						ly.toast("请输入正确的纬度");
						return false;
					}
				}

			}
		
			var success =  $('.form').validate('submitValidate');
		
			submitFom();
		
	
		}else{
			if($("#log").val()=="" || $("#lat").val()=="" || $("#equipmentAddress").val()=="" || $("#equipmentName").val()=="" ){
				ly.toast("请输入完整信息");
				return false;
			}
	
		
				submitFom();
			
		}


    })
	



	//批量删除
	$("#batchDelBtn").click(function(){
		var c = "";
		$("input[name=datachk]:checked").each(function(){
			c += $(this).val()+',';
		});
		deleteFirstCategory(c);
	});



});

/*
 * 提交表单
 */
function submitFom(){
	var equipmentName =$("#equipmentName").val();


	 var log = MapType == 1? $("#log").val() : $("#log2").val();
	 var lat = MapType == 1? $("#lat").val() : $("#lat2").val();
	 var equipmentAddress = MapType ==1 ? $("#equipmentAddress").val() : $("#equipmentAddress2").val() ;

	//  var equipmentAddress = $("#equipmentAddress").val();
	//  var equipmentAddress2 = $("#equipmentAddress2").val();
 	var isUsing = $("#isUsing input:checked").val();

  	var obj = {};
  	var url = site.apiUrl+"/back/attendanceBack/insertOrUpdateEquipment";
  	if(attendanceType == 1){
		//新增
		 obj = {
	    	'equipmentName':equipmentName,
	    	'equipmentType':equipmentTypesss,
	    	'log':log,
	    	'lat':lat,
	    	'equipmentAddress':equipmentAddress,
	    	'isUsing':isUsing
	    };
  	}else{
  		//修改
  		var thisId = $("#id").val();
  		obj = {
  			'equipmentName':equipmentName,
	    	'equipmentType':equipmentTypesss,
	    	'log':log,
	    	'lat':lat,
	    	'equipmentAddress':equipmentAddress,
	    	'isUsing':isUsing,
  			'id':thisId
  		};
  	}
	  console.log(obj);
	//物资类型必须选择
	console.log("equipmentTypesss="+equipmentTypesss);
	if(equipmentTypesss=="3"){
		ly.toast("请选择物资类型");
		return false;
	}

	request({
		url:url,
		data:obj,
		type:"post",
		callback:function(f) {
			console.log(f);
			if(f.code=="rest.success"){
				if(attendanceType == 1){
					ly.alert('保存成功',function(){	            
			    		ly.goto("equipment-list.html");
			        });
				}else{
					ly.alert('修改成功',function(){	           
			    		ly.goto("equipment-list.html");
			        });
				}
			}else{
				ly.toast(f.desc);
			}
		}
	});
  	
}

/**
 * 验证经度的取值范围是否不合法
 * @param log
 */
function validateLogISError(log){

	var logISNo = false;

	/**
	 * 最小经度
	 */
	if (log.length > 0) {
		if (parseFloat(log) < -180) {
			logISNo = true;
		}else if(parseFloat(log) == -180){
			if(log!="-180" &&!/^-[1][8][0][.][0]*[0]{1}$/.test(log)){
				logISNo = true;
			}
		}
	}
	/**
	 * 最大经度
	 */
	if (log.length > 0) {
		if (parseFloat(log) > 180) {
			logISNo = true;
		}else if(parseFloat(log) == 180){
			if(log!="180" && !/^[1][8][0][.][0]*[0]{1}$/.test(log)){
				logISNo = true;
			}
		}
	}

	return logISNo;
}

/**
 * 验证纬度的取值范围是否不合法
 * @param lat
 */
function validateLatISError(lat){
	var latISNo = false;

	/**
	 * 最小纬度
	 */
	if (lat.length > 0) {
		if (parseFloat(lat) < -90) {
			latISNo = true;
		}else if(parseFloat(lat) == -90){
			if(lat!="-90" && lat.split(".")[0] > -90){
				console.log(lat);
			}else if(lat!="-90" && !/^-[9][0][.][0]*[0]{1}$/.test(lat)){
				latISNo = true;
			}
		}
	}
	/**
	 * 最大纬度
	 */
	if (lat.length > 0) {
		if (parseFloat(lat) > 90) {
			latISNo = true;
		}else if(parseFloat(lat) == 90){
			if(lat!="90" && !/^[9][0][.][0]*[0]{1}$/.test(lat)){
				latISNo = true;
			}
		}
	}
	return latISNo;
}

/**
 * 验证经度是否不是数字格式
 * @param log
 * @returns {boolean}
 */
function logIsNotNumber(log){
	var regPos = /^\d+(\.\d+)?$/; //非负浮点数
	var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
	if(!regPos.test(log) && !regNeg.test(log)) {
		return true;
	}
	return false;
}

/**
 * 验证纬度是否不是数字格式
 * @param lat
 * @returns {boolean}
 */
function latIsNotNumber(lat){
	var regPos = /^\d+(\.\d+)?$/; //非负浮点数
	var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
	if(!regPos.test(lat) && !regNeg.test(lat)) {
		return true;
	}
	return false;
}

